﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using SaysayProject.Data;
using SaysayProject.Models;
using SaysayProject.PramaModel;

namespace SaysayProject.Controllers
{
    public class UsersController : Controller
    {
        private CmsDb db = new CmsDb();

        // GET: Users
        public ActionResult Index()
        {
            return View(db.Users.ToList());
        }
        public ActionResult Login()
        {
            //获取所有用户
            var userList = db.Users.ToList();

            if (Session["UserName"] == null)
            {
                return View();
            }
            else
            {
                //获取当前用户id
                var cuuentId = userList.SingleOrDefault(x => x.Username == Session["UserName"].ToString()).Id;

                return RedirectToAction("index/" + cuuentId, "saysay");
            }
        }
        //进入注册页
        public ActionResult Register()
        {
            return View();
        }

        //注册时判断
        public ActionResult doRegister(RegisterModel register)
        {
            //获取输入框的用户名和密码/确认密码
            var username = register.Username.Trim();
            var password = register.Password.Trim();
            var passwordOk = register.PasswordOk.Trim();

            dynamic result;

            //判断当前用户名和密码不能输入为空
            if (username.Length > 0 && password.Length > 0 && passwordOk.Equals(password))
            {
                //判断当前用户名在数据库中是否存在
                var user = db.Users.Where(x => x.Username == username).FirstOrDefault();

                if (user == null)
                {
                    //不存在则插入数据,创建用户
                    db.Users.Add(new Users()
                    {
                        Username = username,
                        Password = password,
                        CreatedAt = DateTime.Now,
                        UpdatedAt = DateTime.Now,
                        Version = 0,
                    });

                    db.SaveChanges();

                    result = Content("<script>alert('注册成功');window.location.href='index';</script>");
                }
                else
                {
                    //如果存在则
                    result = Content("<script>alert('当前用户已存在,可直接登录');window.location.href='Register';</script>");
                }

            }
            else
            {
                result = Content("<script>alert('账号或密码有误，并且不能为空');window.location.href='Register';</script>");
            }



            return result;
        }

        //登录时判断
        [HttpPost]
        public ActionResult doLogin(LoginModel login)
        {
            //获取输入框的用户名和密码
            var username = login.Username.Trim();
            var password = login.Password.Trim();

            //获取所有用户
            var userList = db.Users.ToList();

            //获取当前用户名和密码数据库中有没有
            var DbUserInfo = db.Users.Where(x => x.Username == username && x.Password == password).SingleOrDefault();

            if (DbUserInfo != null)
            {
                Session["UserName"] = username;

                //获取当前用户id
                var cuuentId = userList.SingleOrDefault(x => x.Username == Session["UserName"].ToString()).Id;

                //重定向其他控制器的路由
                return RedirectToAction("index/" + cuuentId, "saysay");
            }
            else
            {
                return Content("<script>alert('账号或者密码不正确');window.location.href='login';</script>");
            }

        }


        // GET: Users/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users users = db.Users.Find(id);
            if (users == null)
            {
                return HttpNotFound();
            }
            return View(users);
        }

        // GET: Users/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Users/Create
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Username,Password,CreatedAt,UpdatedAt,Version,Remarks")] Users users)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(users);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(users);
        }

        // GET: Users/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users users = db.Users.Find(id);
            if (users == null)
            {
                return HttpNotFound();
            }
            return View(users);
        }

        // POST: Users/Edit/5
        // 为了防止“过多发布”攻击，请启用要绑定到的特定属性。有关
        // 详细信息，请参阅 https://go.microsoft.com/fwlink/?LinkId=317598。
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Username,Password,CreatedAt,UpdatedAt,Version,Remarks")] Users users)
        {
            if (ModelState.IsValid)
            {
                db.Entry(users).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(users);
        }

        // GET: Users/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Users users = db.Users.Find(id);
            if (users == null)
            {
                return HttpNotFound();
            }
            return View(users);
        }

        // POST: Users/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Users users = db.Users.Find(id);
            db.Users.Remove(users);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
